#coding=utf-8
import urllib2,urllib,urlparse,simplejson
import socket,os,sys,re,pickle
socket.setdefaulttimeout(60)

from models import Message
from exception import LoginError, FetchCommentsError

debug_level = 0

login_url = 'https://login.sina.com.cn/sso/login.php?username=%s&password=%s&returntype=TEXT'
search_url = 'http://t.sina.com.cn/k/%s'
publish_url = 'http://t.sina.com.cn/mblog/publish.php'
publish_video_url = 'http://t.sina.com.cn/video/publish.php'
delete_url = 'http://t.sina.com.cn/mblog/delete.php?mid=%s'
add_comment_url = 'http://t.sina.com.cn/comment/addcomment.php'
message_url = 'http://t.sina.com.cn/%s/%s'
person_info_url = 'http://t.sina.com.cn/%s/info'

addfollow_url = 'http://t.sina.com.cn/attention/aj_addfollow.php'
unfollow_url = 'http://t.sina.com.cn/attention/aj_delfollow.php'

user_agent = 'Mozilla/5.0 (X11; U; Linux i686; zh-CN; rv:1.9.1.7) Gecko/20100106 Ubuntu/9.10 (karmic) Firefox/3.5.7'

referer = 'http://t.sina.com.cn'

class TsinaRobot(object):
    
  def __init__(self, user, password):
    self.user = user
    self.password = password
    self.opener = self._build_opener()

    self._add_opener_header('user-agent', user_agent)
    self._add_opener_header('referer', referer)
        
  def _add_opener_header(self, k, v):
    i = 0
    for x, y  in self.opener.addheaders:
        if x.lower() == k.lower():break
        i = i + 1
    if i < len(self.opener.addheaders):
        self.opener.addheaders.remove(self.opener.addheaders[i])
    self.opener.addheaders.append((k,v))
            
  def _build_opener(self):
    cookie_support = urllib2.HTTPCookieProcessor()
    opener = urllib2.build_opener(urllib2.HTTPHandler(debuglevel=debug_level), cookie_support)
    return opener
  
  def _get_url(self, url, data=None):
    if data:
        data = urllib.urlencode(data)
        f = self.opener.open(url, data)
    else:
        f = self.opener.open(url)
        
    code, resp, content = f.getcode(), f.info(), f.read()
    return code, resp, content
  
  def follow(self, uid):
    return self._get_url(addfollow_url, {'uid':uid, 'fromuid':self.uid})
  
  def unfollow(self, uid):
    return self._get_url(unfollow_url, {'touid':uid, 'fromuid':self.uid}) 
    
  def login(self):
    response = self.opener.open(login_url%(self.user, self.password))
    try:
      self.uid = eval(response.read())['uid']
      return self.uid
    except:
      raise LoginError(response)
      
  def publish(self, content):
    body = {'content': content}
    req = urllib2.Request(publish_url, data=urllib.urlencode(body))

    f = self.opener.open(req)
    code, resp, content = f.getcode(), f.info(), f.read()
    return code, resp, content
  
  def publish_video(self, content, video_url):
    c, r, c2 = self._get_url(publish_video_url, {'url':video_url} )
    short_url = simplejson.loads(c2)['data']['shorturl']   
    print short_url
    print content
    content = content%short_url
    return self.publish(content)

  def delete(self, message):
    mid = message.message_id
    url = delete_url%mid
    return self._get_url(url)
    
if __name__ == '__main__':
  pass
  
  
